package com.calt.plm.basic.core.reader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import com.calt.plm.basic.core.model.ActionProp;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import com.calt.plm.basic.core.annoation.DataType;
import com.calt.plm.basic.core.model.ActionDefine;
import org.springframework.core.io.support.ResourcePatternResolver;

/**
 * <p>类的简单描述</p>
 *
 * @author wuchao Create on 2022/9/22
 * @version 1.0
 */
public class ActionReader
{
	private static Map<String, ActionDefine> actionMap;

	public void init(ResourcePatternResolver resourcePatternResolver)
	{
		SAXReader saxReader = new SAXReader();
		try {
			Resource[] resources = resourcePatternResolver.getResources("classpath*:META-INF/action/*.xml");
			for (Resource resource : resources)
			{
				Document document = saxReader.read(resource.getInputStream());
				Element rootElement = document.getRootElement();
				List<Element> actionElementList = rootElement.elements("action");
				actionMap = new HashMap<>(actionElementList.size());
				actionElementList.forEach(action -> {
					ActionDefine actionDefine = new ActionDefine();
					actionDefine.setName(action.attribute("name").getValue());
					List<Element> propElementList = action.elements("prop");
					List<ActionProp> actionProps = new ArrayList<>(propElementList.size());
					propElementList.forEach(prop -> {
						ActionProp actionProp = new ActionProp();
						actionProp.setName(prop.attribute("name").getValue());
						actionProp.setType(DataType.values()[Integer.valueOf(prop.attribute("type").getValue())]);
						actionProp.setDesc(prop.attribute("desc").getValue());
						actionProp.setLength(StringUtils.isBlank(prop.attribute("length").getValue()) ? 255 : Integer.parseInt(prop.attribute("length").getValue()));
						actionProp.setPrecision(StringUtils.isBlank(prop.attribute("precision").getValue()) ? 0 : Integer.parseInt(prop.attribute("precision").getValue()));
						actionProp.setIndex("Y".equals(prop.attribute("index").getValue()));
						actionProps.add(actionProp);
					});
					actionDefine.setPropList(actionProps);
					actionMap.put(action.attribute("name").getValue(), actionDefine);
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static ActionDefine get(String name)
	{
		return actionMap.get(name);
	}

}
